package com.yj.springbootstudy.mulThread.imooc;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁读案例：
 * <p>
 * 创建三个线程，线程名称分别为 t1，t2，t3，线程实现方式自行选择；
 * 三个线程同时运行获取读锁，读锁成功后打印线程名和获取结果，并沉睡 2000 毫秒，便于观察其他线程是否可共享读锁；
 * finally 模块中释放锁并打印线程名和释放结果；
 * 运行程序，观察结果。
 */
public class Demo04 {

    static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();


    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + "获取到锁！");
                lock.readLock().lock();
                Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                System.out.println(Thread.currentThread().getName() + "释放锁！");
                lock.readLock().unlock();
            }
        },"t1");


        Thread t2 = new Thread(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + "获取到锁！");
                lock.readLock().lock();
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                System.out.println(Thread.currentThread().getName() + "释放锁！");
                lock.readLock().unlock();
            }
        },"t2");

        Thread t3 = new Thread(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + "获取到锁！");
                lock.readLock().lock();
                Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                System.out.println(Thread.currentThread().getName() + "释放锁！");
                lock.readLock().unlock();
            }
        },"t3");

        t1.start();
        t2.start();
        t3.start();
        t1.join();
        t2.join();
        t3.join();

    }
}
